//
//  NotifyViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/21.
//

import Foundation
import LeanCloud

class NotifyBaseModel : BaseViewModel{
    func jump(type: Int){
        switch type {
        case IMsgType.NO.rawValue:
            break
        case IMsgType.AI_ACT.rawValue:
            receiveAiChat()
            break
        case IMsgType.BUBBLE_ACT.rawValue:
            receiveBubble()
            break
        default:
            showToast("当前版本不支持此功能")
        }
    }
    
    func receiveBubble() {
        if !userManager.isLogin() {
            showLoginPopup()
            return
        }
        if !userManager.isVip() {
            showToast("您当前不是会员无法领取")
        }
        let sign = configManager.getConfig().aiChat.bubbleActSign
        if (sign ?? "")?.isEmpty == true {
            showToast("活动已结束")
        }
        if (sign != userManager.getExtraConfig().bubbleActSign) {
            request {
                var bubbleCount = userManager.getExtraConfig().bubbleCount ?? 0
                bubbleCount += 1
                userManager.getExtraConfig().bubbleCount = bubbleCount
                userManager.getExtraConfig().bubbleActSign = sign
                try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    if let user = userManager.user {
                        try await LeancloudManager.instance.save(todo: user)
                        userManager.update()
                    }
                }
                return true
            } suc: { _ in
                showToast("领取成功")
            } fail: { _ in
                showToast("领取失败")
            }
        } else {
            showToast("已经领取过了，请下次再来")
        }
    }
    
    func receiveAiChat() {
        if !userManager.isLogin() {
            showLoginPopup()
            return
        }
        if userManager.isInfinite() {
            showToast("当前是AI不限制，无法领取")
        }
        let sign = configManager.getConfig().aiChat.aiActSign
        if (sign ?? "")?.isEmpty == true {
            showToast("活动已结束")
        }
        if (sign != userManager.getExtraConfig().aiActSign) {
            request {
                var count = userManager.isVip() ? configManager.getConfig().aiChat.aiActVipCount : configManager.getConfig().aiChat.aiActCount
                userManager.getExtraConfig().aiActSign = sign
                try await retry(maxRetries: 5, retryDelayMillis: 500) {
                    if let user = userManager.user {
                        try await LeancloudManager.instance.save(todo: user)
                        userManager.update()
                    }
                }
                return count
            } suc: {
                userManager.doAiChatCount(Double($0))
                showTipsDialog(text: "已成功领取\($0)次AI次数") {}
            } fail: { _ in
                showToast("领取失败")
            }
        } else {
            showToast("已经领取过了，请下次再来")
        }
    }
}
